package secondkill.controller;


import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.json.JSONUtil;
import com.wf.captcha.ArithmeticCaptcha;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.data.redis.core.script.RedisScript;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import secondkill.Exception.GlobalException;
import secondkill.pojo.SecKillMessage;
import secondkill.pojo.TSeckillOrder;
import secondkill.pojo.TUser;
import secondkill.rabbtmq.MQSender;
import secondkill.service.ITGoodsService;
import secondkill.service.ITOrderService;
import secondkill.service.ITSeckillOrderService;
import secondkill.validator.AccessLimit;
import secondkill.vo.GoodsVo;
import secondkill.vo.RespBean;
import secondkill.vo.RespBeanEnum;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;


/**
 * 秒杀控制类
 * @Auther  丁子川
 * @create 2022/1/20 21:38
 */

// .cast 类型强转快捷键
@Slf4j
@Controller
@RequestMapping("/secondKill")
public class SecKillController implements InitializingBean {
    @Autowired
    private ITGoodsService goodsService;
    @Autowired
    private ITSeckillOrderService seckillOrderService;
    @Autowired
    private ITOrderService orderService;
    @Autowired
    private RedisTemplate redisTemplate;
    @Autowired
    private MQSender mqSender;
    @Autowired
    private RedisScript<Long> redisScript;

    private Map<Long, Boolean> EmptyStockMap = new HashMap<Long, Boolean>();

    //版本一
/*    @RequestMapping("/doSecondKill")
    public String doSecKill(Model model, TUser user, Long goodsId) {

        //未登录判断
        if (user == null) {
            return "login";
        }
        model.addAttribute("user", user);

        GoodsVo goods = goodsService.findGoodsVoByGoodId(goodsId);
        log.info("goods:{}",goods);
        //判断库存是否足够
        if (goods.getStockCount() < 1) {
            model.addAttribute("errorMessage", RespBeanEnum.EMPTY_STOCK.getMessage());
            return "secondKillFail";
        }

        //判断是否重复抢购
        TSeckillOrder secKillOrder = seckillOrderService.getOne(new QueryWrapper<TSeckillOrder>().eq("user_id", user.getId()).eq("goods_id", goodsId));
        log.info("secKillOrder:{}",secKillOrder);

        if (secKillOrder != null) {
            model.addAttribute("errorMessage", RespBeanEnum.LIMITED_ERROR.getMessage());
            return "secondKillFail";
        }

        TOrder order = orderService.secKill(user, goods);
        model.addAttribute("order", order);
        model.addAttribute("goods", goods);
        return "orderDetail";
    }*/

    //版本二 秒杀静态化
    @RequestMapping(value = "/{path}/doSecondKill", method = RequestMethod.POST)
    @ResponseBody
    public RespBean doSecKill(@PathVariable String path, TUser user, Long goodsId) {

        log.info("--------------path:{}",path);
        log.info("--------------goodsId:{}",goodsId);
        if (ObjectUtil.isEmpty(user)) {
            return RespBean.error(RespBeanEnum.SESSION_ERROR);
        }

        //获取redisTemplate
        ValueOperations valueOperations = redisTemplate.opsForValue();

        //验证码校验
        boolean check = orderService.checkPath(user, goodsId, path);
        if (!check) {
            return RespBean.error(RespBeanEnum.REQUEST_ILLEGAL);
        }

        //判断是否重复抢购 将用户如果抢购成功的消息存放进redis中进行判断
        TSeckillOrder secKillOrder = (TSeckillOrder) redisTemplate.opsForValue().get("order:" + user.getId() + ":" + goodsId);
        if (secKillOrder != null) {
            return RespBean.error(RespBeanEnum.REPEAT_ERROR);
        }

        //库存标记，减少redis的访问
        if (EmptyStockMap.get(goodsId)) {
            return RespBean.error(RespBeanEnum.EMPTY_STOCK);
        }

        //预减库存操作，调用一次减一（原子性的）
        Long stock = valueOperations.decrement("secKillGood:" + goodsId);

        //分布式锁 脚本lua来保证原子性 判断库存
        //Long stock = (Long) redisTemplate.execute(redisScript, Collections.singletonList("secKillGood:" + goodsId), Collections.EMPTY_LIST);

        log.info("--------------stock:{}",stock);
        if (stock < 0) {
            EmptyStockMap.put(goodsId, true);
            valueOperations.increment("secKillGood:" + goodsId);
            return RespBean.error(RespBeanEnum.EMPTY_STOCK);
        }

        //rabbitMQ可以快速返回请求 流量削峰
        SecKillMessage seckillMessage = new SecKillMessage(user, goodsId);
        mqSender.sendSeckillMessage(JSONUtil.toJsonStr(seckillMessage));
        return RespBean.success(0);
    }


    /**
     * 获取秒杀结果
     * return  orderId:成功 -1 秒杀失败，  0 排队中
     * @param user
     * @param goodsId
     * @return
     */
    @RequestMapping(value = "/getResult", method = RequestMethod.GET)
    @ResponseBody
    public RespBean getResult(TUser user, Long goodsId) {

        if (ObjectUtil.isEmpty(user)) {
            return RespBean.error(RespBeanEnum.SESSION_ERROR);
        }

        Long orderId = seckillOrderService.getResult(user, goodsId);
        log.info("=============orderId:{}",orderId);
        return RespBean.success(orderId);
    }

    /**
     * 初始化执行的方法，将商品加载到redis中
     * @return void
     * @create 2022/1/24 23:28
     */
    @Override
    public void afterPropertiesSet()  {
        List<GoodsVo> list = goodsService.findGoodsVoList();
        if (CollectionUtil.isEmpty(list)) {
            return;
        }

        list.forEach(goodsVo -> {
            redisTemplate.opsForValue().set("secKillGood:" + goodsVo.getId(), goodsVo.getStockCount());
            EmptyStockMap.put(goodsVo.getId(), false);
        });
    }


    /**
     * 获取秒杀地址
     * @param user
     * @param goodsId
     * @return
     */
    @AccessLimit(second=5, maxCount=5, needLogin=true)
    @RequestMapping(value = "/path", method = RequestMethod.GET)
    @ResponseBody
    public RespBean getPath(TUser user, Long goodsId, HttpServletRequest request, String captcha) {
        if (ObjectUtil.isEmpty(user)) {
            return RespBean.error(RespBeanEnum.SESSION_ERROR);
        }
        log.info("-----------goodId:{}", goodsId);

        //校验验证码
        boolean check = orderService.checkCaptcha(user, goodsId, captcha);
        if (!check) {
            return RespBean.error(RespBeanEnum.ERROR_CAPTCHA);
        }

        //限流操作,5秒钟访问五次 主流限流算法: 计数器 令牌桶 漏桶
        //后使用注释方法实现计数器的限流实现
        /*ValueOperations valueOperations = redisTemplate.opsForValue();

        String uri = request.getRequestURI();
        Integer count = (Integer) valueOperations.get(uri + ":" + user.getId());

        if (count == null) {
            valueOperations.set(uri + ":" + user.getId(), 1, 5, TimeUnit.SECONDS);
        } else if (count < 5) {
            valueOperations.increment(uri + ":" + user.getId());
        } else {
            return RespBean.error(RespBeanEnum.ACCESS_LIMIT_REACHED);
        }*/

        String str = orderService.createPath(user, goodsId);
        log.info("-----------str:{}", str);
        return RespBean.success(str);
    }

    /**
     * 验证码校验
     * @param user 
     * @param goodsId
     * @param response
     * @return void 
     * @create 2022/1/25 17:02
     */
    @RequestMapping(value = "/captcha", method = RequestMethod.GET)
    public void verifyCode(TUser user, Long goodsId, HttpServletResponse response) {

        if (ObjectUtil.isEmpty(user) || goodsId < 0) {
            throw new GlobalException(RespBeanEnum.REQUEST_ILLEGAL);
        }
        //设置请求头为输出图片的类型
        response.setContentType("images/jpg");
        response.setHeader("Pargam", "no-cache");
        response.setHeader("Cache-Control", "no-cache");
        response.setDateHeader("Expires", 0);
        //生成验证码，将结果放入Redis
        ArithmeticCaptcha captcha = new ArithmeticCaptcha(120, 30, 3);
        redisTemplate.opsForValue().set("captcha:" + user.getId() + ":" + goodsId, captcha.text(), 300, TimeUnit.SECONDS);

        try {
            captcha.out(response.getOutputStream());
        } catch (IOException e) {
            log.error("验证码生成失败", e.getMessage());
        }
    }
}